import 'package:bboy_music_box_2023/bean/bean_musci_item.dart';
import 'package:bboy_music_box_2023/bean/bean_music_manager.dart';
import 'package:bboy_music_box_2023/bean/bean_music_query.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_home.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_muisc.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_play.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_query.dart';
import 'package:bboy_music_box_2023/res/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xlider/flutter_xlider.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MusicView extends StatefulWidget {
  MusicView({Key? key}) : super(key: key);

  @override
  State<MusicView> createState() => _MusicViewState();
}

class _MusicViewState extends State<MusicView> with TickerProviderStateMixin {
  late AnimationController playAnimController;
  late double progress = 50;

  @override
  void initState() {
    super.initState();

    playAnimController = AnimationController(vsync: this)
      ..drive(Tween(begin: 0, end: 1))
      ..duration = Duration(milliseconds: 500);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(child: buildMusicBody()),
      ],
    );
  }

  Widget buildMusicBody() {
    return SafeArea(
      child: Obx(() {
        MusicManger musicManager = PlayCtrl.to.selectMusic.value;
        String name = musicManager.music!.title;
        if (name.isEmpty) {
          name = musicManager.music!.name;
          name = name.replaceAll(".mp3", '').replaceAll(".MP3", '');
        }
        String artist = musicManager.music!.artist;

        return Container(
          color: Colors.white,
          child: Column(
            children: [
              SizedBox(height: 30.0),
              Container(
              margin: const EdgeInsets.symmetric(horizontal: 20.0),
              child: Text(
                name,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 22.0,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.left,
              ),
            ),
              SizedBox(height: 20.0),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20.0),
                child: Text(
                  artist,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.0,
                  ),
                  textAlign: TextAlign.left,
                ),
              ),
              SizedBox(height: 10.0),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20.0),
                child: Text(
                  '上传者：${musicManager.music!.uploader}',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.0,
                  ),
                  textAlign: TextAlign.left,
                ),
              ),
              SizedBox(height: 10.0),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20.0),
                child: Text(
                  '${musicManager.music!.desc}',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12.0,
                  ),
                  textAlign: TextAlign.left,
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      width: 300.0,
                      height: 300.0,
                      decoration: ShapeDecoration(
                          image: DecorationImage(
                              image: NetworkImage(musicManager.music!.imgUrl),
                              fit: BoxFit.contain),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          )),
                    ),
                    SizedBox(height: 20.0),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: Row(
                        children: [
                          Expanded(
                            child: FlutterSlider(
                              values: [musicManager.seek * 1.0],
                              min: 0,
                              max: musicManager.duration * 1.0,
                              trackBar: FlutterSliderTrackBar(
                                  activeTrackBarHeight: 6.0,
                                  activeTrackBar: BoxDecoration(
                                    color: Colors.deepOrange,
                                    borderRadius: BorderRadius.circular(10.0),
                                  ),
                                  inactiveTrackBarHeight: 6.0,
                                  inactiveTrackBar: BoxDecoration(
                                    color: Colors.grey[300],
                                    borderRadius: BorderRadius.circular(10.0),
                                  )),
                              onDragging:
                                  (handlerIndex, lowerValue, upperValue) {
                                print(
                                    'lowerValue: $lowerValue, upperValue: $upperValue');
                                PlayCtrl.to.seek(lowerValue.toInt());
                              },
                              handler: FlutterSliderHandler(
                                decoration: BoxDecoration(),
                                child: Container(
                                  width: 30.0,
                                  height: 30.0,
                                  decoration: ShapeDecoration(
                                    color: Colors.white,
                                    shadows: const [
                                      BoxShadow(
                                          color: Colors.black26,
                                          blurRadius: 3,
                                          spreadRadius: 0.5,
                                          offset: Offset(0, 3))
                                    ],
                                    // image: DecorationImage(
                                    //   image: NetworkImage(musicManager.music!.imgUrl),
                                    //   fit: BoxFit.contain,
                                    // ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(30.0),
                                    ),
                                  ),
                                  child: Icon(
                                    Icons.music_note,
                                    color: Colors.deepOrange,
                                  ),
                                ),
                              ),
                              tooltip: FlutterSliderTooltip(
                                disabled: true,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 30.0),
                      child: Row(
                        children: [
                          Container(
                            child: Text(
                              '${(musicManager.seek ~/ 60).toString().padLeft(2, '0')}'
                              ':${(musicManager.seek % 60).toString().padLeft(2, '0')}',
                              style: const TextStyle(
                                fontSize: 10.0,
                                color: Colors.black54,
                              ),
                            ),
                          ),
                          Expanded(child: Container()),
                          Container(
                            child: Text(
                              '${(musicManager.duration ~/ 60).toString().padLeft(2, '0')}'
                              ':${(musicManager.duration % 60).toString().padLeft(2, '0')}',
                              style: const TextStyle(
                                fontSize: 10.0,
                                color: Colors.black54,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    buildOperationRow(),
                  ],
                ),
              ),
              buildBottomMenu(),
              SizedBox(height: 30.0),
            ],
          ),
        );
      }),
    );
  }

  Widget playCard(MusicManger manger) {
    return Container(
      decoration: BoxDecoration(
          border: Border(top: BorderSide(color: Colors.black54, width: 0.1))),
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      child: Row(
        children: [
          Container(
            width: 30.0,
            height: 30.0,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: Image.network(manger.music!.imgUrl),
          ),
          Expanded(
            child: Container(
              child: ListTile(
                title: Container(
                  child: Text(
                    manger.music!.name,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 14.0,
                    ),
                    textAlign: TextAlign.left,
                    maxLines: 1,
                    softWrap: false,
                    overflow: TextOverflow.fade,
                  ),
                ),
                subtitle: Container(
                  child: Text(
                    '${(manger.seek ~/ 60).toString().padLeft(2, '0')}'
                    ':${(manger.seek % 60).toString().padLeft(2, '0')}/'
                    '${(manger.duration ~/ 60).toString().padLeft(2, '0')}'
                    ':${(manger.duration % 60).toString().padLeft(2, '0')}',
                    style: const TextStyle(
                      fontSize: 8.0,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          ),
          Container(
            width: 40.0,
            height: 40.0,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: Obx(() {
              bool isPlaying = PlayCtrl.to.isPlaying.value;
              isPlaying
                  ? playAnimController.forward()
                  : playAnimController.reverse();
              return InkWell(
                onTap: () {
                  HomeCtrl.to.playAndPause();
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(100.0),
                  ),
                  child: Center(
                    child: AnimatedIcon(
                      color: Colors.white,
                      size: 30.0,
                      icon: AnimatedIcons.play_pause,
                      progress: playAnimController,
                    ),
                  ),
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  Widget buildOperationRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            PlayCtrl.to.skipPrevious();
          },
          child: Container(
            decoration: BoxDecoration(),
            child: Center(
              child: Icon(
                Icons.skip_previous_rounded,
                size: 40.0,
                color: Colors.black,
              ),
            ),
          ),
        ),
        SizedBox(width: 40),
        Container(
          width: 80.0,
          height: 80.0,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5.0),
          ),
          child: Obx(() {
            bool isPlaying = PlayCtrl.to.isPlaying.value;
            isPlaying
                ? playAnimController.forward()
                : playAnimController.reverse();
            return InkWell(
              onTap: () {
                HomeCtrl.to.playAndPause();
              },
              child: Listener(
                onPointerDown: (event) {
                  MusicCtrl.to.isPlayBtnDown.value = true;
                  MusicCtrl.to.isPlayBtnDown.refresh();
                  print('按钮按下！');
                },
                onPointerUp: (event) {
                  MusicCtrl.to.isPlayBtnDown.value = false;
                  MusicCtrl.to.isPlayBtnDown.refresh();
                  print('按钮抬起！');
                },
                onPointerCancel: (event) {
                  MusicCtrl.to.isPlayBtnDown.value = false;
                  MusicCtrl.to.isPlayBtnDown.refresh();
                  print('按钮取消！');
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(100.0),
                    boxShadow: MusicCtrl.to.isPlayBtnDown.value
                        ? []
                        : const [
                            BoxShadow(
                                color: Colors.black26,
                                blurRadius: 4,
                                spreadRadius: 0.5,
                                offset: Offset(0, 4))
                          ],
                  ),
                  child: Center(
                    child: AnimatedIcon(
                      color: Colors.white,
                      size: 50.0,
                      icon: AnimatedIcons.play_pause,
                      progress: playAnimController,
                    ),
                  ),
                ),
              ),
            );
          }),
        ),
        SizedBox(width: 40),
        InkWell(
          onTap: () {
            PlayCtrl.to.skipNext();
          },
          child: Container(
            decoration: BoxDecoration(),
            child: Center(
              child: Icon(
                Icons.skip_next_rounded,
                size: 40.0,
                color: Colors.black,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildBottomMenu() {
    return Container(
      child: Row(
        children: [
          Expanded(child: buildPlayRepeatModeIcon()),
          Expanded(
            child: Container(
              child: Icon(
                Icons.favorite_border_rounded,
                size: 25.0,
                color: Colors.black54,
              ),
            ),
          ),
          Expanded(
            child: Container(
              child: Icon(
                Icons.menu_rounded,
                size: 25.0,
                color: Colors.black54,
              ),
            ),
          ),
          Expanded(
            child: Container(
              child: Icon(
                Icons.more_horiz_rounded,
                size: 25.0,
                color: Colors.black54,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildPlayRepeatModeIcon() {
    return Obx(() {
      var playMode = MusicCtrl.to.playReplayMode.value;
      Widget child;
      IconData iconData;
      ValueKey key;
      switch (playMode) {
        case PlayRepeatMode.loop:
          iconData = Icons.repeat_rounded;
          key = const ValueKey(PlayRepeatMode.loop);
          break;
        case PlayRepeatMode.repeat:
          iconData = Icons.repeat_one_rounded;
          key = const ValueKey(PlayRepeatMode.repeat);
          break;
        case PlayRepeatMode.shuffle:
          iconData = Icons.shuffle_rounded;
          key = const ValueKey(PlayRepeatMode.shuffle);
          break;
      }
      return InkWell(
        onTap: () {
          var mode = MusicCtrl.to.playReplayMode.value;
          switch (mode) {
            case PlayRepeatMode.loop:
              MusicCtrl.to.playReplayMode.value = PlayRepeatMode.repeat;
              break;
            case PlayRepeatMode.repeat:
              MusicCtrl.to.playReplayMode.value = PlayRepeatMode.shuffle;
              break;
            case PlayRepeatMode.shuffle:
              MusicCtrl.to.playReplayMode.value = PlayRepeatMode.loop;
              break;
          }
          MusicCtrl.to.playReplayMode.refresh();
        },
        child: Container(
          color: Colors.white,
          child: AnimatedSwitcher(
            duration: Duration(milliseconds: 200),
            child: Icon(
              iconData,
              key: key,
              size: 25.0,
              color: Colors.black54,
            ),
            transitionBuilder: (Widget child, Animation<double> animation) {
              return FadeTransition(
                opacity: animation,
                child: child,
              );
            },
          ),
        ),
      );
    });
  }
}
